<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>密钥发行 - 密钥管理服务</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- 共享响应式样式 -->
    <link href="shared_responsive.css" rel="stylesheet">
    <!-- 通用工具函数 -->
    <script src="../common/common.js"></script>
    <style>
        body {
            background-color: #f8fafc;
            background-image: radial-gradient(rgba(59, 130, 246, 0.05) 1px, transparent 1px);
            background-size: 20px 20px;
            background-position: 0 0, 10px 10px;
            color: #334155;
        }
        .card {
            background-color: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(20px);
            border: 1px solid rgba(59, 130, 246, 0.4);
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.02);
            transition: all 0.3s ease;
        }
        .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.04);
        }
        .btn {
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        .btn::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background-color: rgba(255, 255, 255, 0.5);
            transform: translate(-50%, -50%);
            transition: width 0.6s, height 0.6s;
        }
        .btn:active::after {
            width: 300px;
            height: 300px;
        }
        .btn-primary {
            background-color: rgba(59, 130, 246, 0.15);
            color: #3b82f6;
            border: 1px solid rgba(59, 130, 246, 0.3);
        }
        .btn-primary:hover {
            background-color: rgba(59, 130, 246, 0.25);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(59, 130, 246, 0.15);
        }
        .btn-success {
            background-color: rgba(34, 197, 94, 0.15);
            color: #16a34a;
            border: 1px solid rgba(34, 197, 94, 0.3);
        }
        .btn-success:hover {
            background-color: rgba(34, 197, 94, 0.25);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(34, 197, 94, 0.15);
        }
        .btn-danger {
            background-color: rgba(239, 68, 68, 0.15);
            color: #dc2626;
            border: 1px solid rgba(239, 68, 68, 0.3);
        }
        .btn-danger:hover {
            background-color: rgba(239, 68, 68, 0.25);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(239, 68, 68, 0.15);
        }
        .input-field {
            background-color: rgba(255, 255, 255, 0.8);
            border: 1px solid rgba(59, 130, 246, 0.3);
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        .input-field:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            background-color: rgba(255, 255, 255, 0.95);
        }
        .table-row {
            transition: all 0.2s ease;
        }
        .table-row:hover {
            background-color: rgba(59, 130, 246, 0.05);
            transform: translateX(2px);
        }
        .back-btn {
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        .back-btn:hover {
            background-color: rgba(59, 130, 246, 0.1);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(59, 130, 246, 0.15);
        }
        .tab-btn {
            transition: all 0.3s ease;
            border-bottom: 2px solid transparent;
            position: relative;
        }
        .tab-btn::before {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 2px;
            background-color: #3b82f6;
            transform: scaleX(0);
            transform-origin: left;
            transition: transform 0.3s ease;
        }
        .tab-btn.active {
            color: #3b82f6;
            background-color: rgba(59, 130, 246, 0.05);
        }
        .tab-btn.active::before {
            transform: scaleX(1);
        }
        .tab-btn:hover {
            background-color: rgba(59, 130, 246, 0.05);
        }
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        .status-badge:hover {
            transform: scale(1.05);
        }
        .status-pending {
            background-color: rgba(234, 179, 8, 0.15);
            color: #d97706;
        }
        .status-approved {
            background-color: rgba(34, 197, 94, 0.15);
            color: #16a34a;
        }
        .status-rejected {
            background-color: rgba(239, 68, 68, 0.15);
            color: #dc2626;
        }
        .status-completed {
            background-color: rgba(59, 130, 246, 0.15);
            color: #3b82f6;
        }
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s ease, visibility 0.3s ease;
        }
        .modal-overlay.modal-show {
            opacity: 1;
            visibility: visible;
        }
        .modal {
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            max-width: 500px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            transform: translateY(-20px) scale(0.95);
            transition: transform 0.3s ease, opacity 0.3s ease;
            opacity: 0;
        }
        .modal-overlay.modal-show .modal {
            transform: translateY(0) scale(1);
            opacity: 1;
        }
        /* 动画效果 */
        @keyframes pulse {
            0%, 100% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.05);
            }
        }
        @keyframes float {
            0%, 100% {
                transform: translateY(0);
            }
            50% {
                transform: translateY(-4px);
            }
        }
        @keyframes fadeInDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        @keyframes slideInRight {
            from {
                opacity: 0;
                transform: translateX(30px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }
        .pulse {
            animation: pulse 2s infinite;
        }
        .float {
            animation: float 3s ease-in-out infinite;
        }
        .fade-in-down {
            animation: fadeInDown 0.5s ease-out;
        }
        .slide-in-right {
            animation: slideInRight 0.5s ease-out;
        }
        /* Toast 样式增强 */
        #toast {
            backdrop-filter: blur(10px);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }
        /* 表格样式增强 */
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th {
            background-color: rgba(59, 130, 246, 0.05);
            font-weight: 600;
            padding: 0.75rem 1rem;
            text-align: left;
            border-bottom: 2px solid rgba(59, 130, 246, 0.2);
        }
        td {
            padding: 0.75rem 1rem;
            border-bottom: 1px solid rgba(59, 130, 246, 0.1);
        }
        /* 加载状态 */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid rgba(59, 130, 246, 0.3);
            border-radius: 50%;
            border-top-color: #3b82f6;
            animation: spin 1s ease-in-out infinite;
        }
        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }
    </style>
</head>
<body>
    <!-- 背景网格层 -->
    <article>
    <!-- 主要内容层 -->
    <section id="main-content" class="p-6">
        <!-- Toast 容器 -->
        <div id="toast" class="fixed bottom-4 right-4 px-4 py-2 rounded-lg text-white shadow-lg transform transition-all duration-300 scale-0 bg-blue-600"></div>
        <!-- 页面标题区 -->
        <header class="mb-6 pb-4 border-b border-[rgba(99,116,139,0.2)]">
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div>
                    <h1 class="clamp(1.5rem,3vw,2rem) font-bold text-[#334155]">密钥发行</h1>
                    <p class="text-[#64748b] text-sm mt-1">管理密钥的申请、审核和发行流程</p>
                </div>
                <a href="index.html" class="back-btn bg-blue-500 text-white px-4 py-2 rounded-lg inline-flex items-center gap-2 hover:shadow-md">
                    <i class="fas fa-arrow-left"></i>
                    <span>返回主页</span>
                </a>
            </div>
        </header>

        <!-- 标签页导航 -->
        <div class="card mb-6">
            <div class="flex border-b border-gray-200">
                <button class="tab-btn px-6 py-4 font-medium active" onclick="switchTab('config', event)">发行配置</button>
                <button class="tab-btn px-6 py-4 font-medium" onclick="switchTab('requests', event)">申请管理</button>
                <button class="tab-btn px-6 py-4 font-medium" onclick="switchTab('distributions', event)">发行记录</button>
            </div>
        </div>

        <!-- 申请详情模态框 -->
        <div id="requestDetailModal" class="modal-overlay hidden">
            <div class="modal p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold">申请详情</h3>
                    <button onclick="closeModal('requestDetailModal')" class="text-gray-500 hover:text-gray-700">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div id="requestDetailContent"></div>
            </div>
        </div>

        <!-- 发行记录详情模态框 -->
        <div id="distributionDetailModal" class="modal-overlay hidden">
            <div class="modal p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold">发行记录详情</h3>
                    <button onclick="closeModal('distributionDetailModal')" class="text-gray-500 hover:text-gray-700">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div id="distributionDetailContent"></div>
            </div>
        </div>

        <!-- 发行配置标签页 -->
        <div id="configTab" class="tab-content">
            <div class="card p-6 mb-6">
                <h2 class="text-xl font-semibold mb-4">密钥发行配置</h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">发行模式</label>
                        <select class="input-field w-full px-4 py-2" id="distributionMode" placeholder="选择发行模式">
                            <option value="online">在线发行</option>
                            <option value="offline">离线发行</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">审批流程</label>
                        <select class="input-field w-full px-4 py-2" id="approvalFlow" placeholder="选择审批流程">
                            <option value="single">单人审批</option>
                            <option value="multi">多人审批</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">密钥有效期（天）</label>
                        <input type="number" class="input-field w-full px-4 py-2" id="keyValidity" value="365">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">默认算法</label>
                        <select class="input-field w-full px-4 py-2" id="defaultAlgorithm" placeholder="选择默认算法">
                            <option value="SM2">SM2</option>
                            <option value="RSA">RSA</option>
                            <option value="SM4">SM4</option>
                            <option value="AES">AES</option>
                        </select>
                    </div>
                </div>
                <div class="mt-6">
                    <button class="btn btn-primary px-4 py-2 rounded-lg" onclick="saveDistributionConfig()">
                        <i class="fas fa-save"></i> 保存配置
                    </button>
                </div>
            </div>
        </div>

        <!-- 申请管理标签页 -->
        <div id="requestsTab" class="tab-content hidden">
            <div class="card p-6">
                <h2 class="text-xl font-semibold mb-4">密钥申请管理</h2>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="border-b border-gray-200">
                                <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">申请ID</th>
                                <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">申请人</th>
                                <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">申请时间</th>
                                <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">密钥类型</th>
                                <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">算法</th>
                                <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">状态</th>
                                <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">操作</th>
                            </tr>
                        </thead>
                        <tbody id="requestsTableBody">
                            <!-- 申请数据将通过JavaScript动态生成 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 发行记录标签页 -->
        <div id="distributionsTab" class="tab-content hidden">
            <div class="card p-6">
                <h2 class="text-xl font-semibold mb-4">密钥发行记录</h2>
                <div class="overflow-x-auto">
                    <table class="data-table">
                        <thead>
                            <tr class="border-b border-gray-200">
                                <th class="py-3 px-4 text-left text-sm font-medium text-gray-500">发行ID</th>
                                <th class="py-3 px-4 text-left text-sm font-medium text-gray-500">密钥ID</th>
                                <th class="py-3 px-4 text-left text-sm font-medium text-gray-500">接收方</th>
                                <th class="py-3 px-4 text-left text-sm font-medium text-gray-500">关联申请</th>
                                <th class="py-3 px-4 text-left text-sm font-medium text-gray-500">发行时间</th>
                                <th class="py-3 px-4 text-left text-sm font-medium text-gray-500">有效期</th>
                                <th class="py-3 px-4 text-left text-sm font-medium text-gray-500">状态</th>
                                <th class="py-3 px-4 text-left text-sm font-medium text-gray-500">操作</th>
                            </tr>
                        </thead>
                        <tbody id="distributionsTableBody">
                            <!-- 发行记录将通过JavaScript动态生成 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- 引入通用工具函数 -->
    <script src="common.js"></script>

    <script>
        // 初始化数据
        function initData() {
            // 显示加载状态

            // 初始化密钥发行配置
            if (!localStorage.getItem('distributionConfig')) {
                const initialConfig = {
                    mode: 'online',
                    approvalFlow: 'single',
                    keyValidity: 365,
                    defaultAlgorithm: 'SM2'
                };
                localStorage.setItem('distributionConfig', JSON.stringify(initialConfig));
            }

            // 初始化密钥申请数据
            if (!localStorage.getItem('keyRequests')) {
                const initialRequests = [
                    { id: 'REQ-001', applicant: '下级平台A', time: '2024-01-15 10:30', keyType: 'KEK', algorithm: 'AES', status: 'pending', details: '申请128位AES密钥用于数据加密' },
                    { id: 'REQ-002', applicant: '下级平台B', time: '2024-01-16 14:20', keyType: 'DEK', algorithm: 'SM4', status: 'approved', details: '申请256位SM4密钥用于文件加密' },
                    { id: 'REQ-003', applicant: '下级平台C', time: '2024-01-17 09:15', keyType: '主密钥', algorithm: 'SM2', status: 'rejected', details: '申请256位SM2主密钥' },
                    { id: 'REQ-004', applicant: '下级平台D', time: '2024-01-18 16:45', keyType: '数据密钥', algorithm: 'AES', status: 'pending', details: '申请256位AES数据密钥用于数据库加密' },
                    { id: 'REQ-005', applicant: '下级平台E', time: '2024-01-19 09:30', keyType: '签名密钥', algorithm: 'RSA', status: 'approved', details: '申请2048位RSA签名密钥用于文档签名' }
                ];
                localStorage.setItem('keyRequests', JSON.stringify(initialRequests));
            }

            // 初始化密钥发行记录
            if (!localStorage.getItem('keyDistributions')) {
                const initialDistributions = [
                    { id: 'DIS-001', keyId: 'KMS-004', receiver: '下级平台B', time: '2024-01-16 15:00', validity: '365天', status: 'completed', file: 'kms-distribution-20240116.zip', fileSize: '2.8 MB', fileType: 'ZIP', checksum: 'SHA256: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2' },
                    { id: 'DIS-002', keyId: 'KMS-005', receiver: '下级平台D', time: '2024-01-14 11:30', validity: '365天', status: 'completed', file: 'kms-distribution-20240114.zip', fileSize: '3.2 MB', fileType: 'ZIP', checksum: 'SHA256: b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3' },
                    { id: 'DIS-003', keyId: 'KMS-006', receiver: '下级平台E', time: '2024-01-13 16:45', validity: '365天', status: 'completed', file: 'kms-distribution-20240113.zip', fileSize: '1.9 MB', fileType: 'ZIP', checksum: 'SHA256: c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4' },
                    { id: 'DIS-004', keyId: 'KMS-007', receiver: '下级平台A', time: '2024-01-20 14:20', validity: '180天', status: 'completed', file: 'kms-distribution-20240120.zip', fileSize: '4.5 MB', fileType: 'ZIP', checksum: 'SHA256: d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5' },
                    { id: 'DIS-005', keyId: 'KMS-008', receiver: '下级平台C', time: '2024-01-21 10:15', validity: '365天', status: 'completed', file: 'kms-distribution-20240121.zip', fileSize: '2.1 MB', fileType: 'ZIP', checksum: 'SHA256: e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6' }
                ];
                localStorage.setItem('keyDistributions', JSON.stringify(initialDistributions));
            }

            // 隐藏加载状态
            setTimeout(() => {
                hideToast();
            }, 1000);
        }

        // 重置数据（用于调试）
        function resetDistributionData() {
            if (confirm('确定要重置所有密钥发行数据吗？')) {
                // 初始化密钥发行记录
                const initialDistributions = [
                    { id: 'DIS-001', keyId: 'KMS-004', receiver: '下级平台B', time: '2024-01-16 15:00', validity: '365天', status: 'completed', file: 'kms-distribution-20240116.zip', fileSize: '2.8 MB', fileType: 'ZIP', checksum: 'SHA256: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2' },
                    { id: 'DIS-002', keyId: 'KMS-005', receiver: '下级平台D', time: '2024-01-14 11:30', validity: '365天', status: 'completed', file: 'kms-distribution-20240114.zip', fileSize: '3.2 MB', fileType: 'ZIP', checksum: 'SHA256: b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3' },
                    { id: 'DIS-003', keyId: 'KMS-006', receiver: '下级平台E', time: '2024-01-13 16:45', validity: '365天', status: 'completed', file: 'kms-distribution-20240113.zip', fileSize: '1.9 MB', fileType: 'ZIP', checksum: 'SHA256: c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4' },
                    { id: 'DIS-004', keyId: 'KMS-007', receiver: '下级平台A', time: '2024-01-20 14:20', validity: '180天', status: 'completed', file: 'kms-distribution-20240120.zip', fileSize: '4.5 MB', fileType: 'ZIP', checksum: 'SHA256: d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5' },
                    { id: 'DIS-005', keyId: 'KMS-008', receiver: '下级平台C', time: '2024-01-21 10:15', validity: '365天', status: 'completed', file: 'kms-distribution-20240121.zip', fileSize: '2.1 MB', fileType: 'ZIP', checksum: 'SHA256: e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6' }
                ];
                localStorage.setItem('keyDistributions', JSON.stringify(initialDistributions));
                showToast('数据重置成功！', 'success');
                loadKeyDistributions();
            }
        }

        // 加载发行配置
        function loadDistributionConfig() {
            const config = JSON.parse(localStorage.getItem('distributionConfig')) || {};
            document.getElementById('distributionMode').value = config.mode || 'online';
            document.getElementById('approvalFlow').value = config.approvalFlow || 'single';
            document.getElementById('keyValidity').value = config.keyValidity || 365;
            document.getElementById('defaultAlgorithm').value = config.defaultAlgorithm || 'SM2';
        }

        // 保存发行配置
        function saveDistributionConfig() {
            const validity = parseInt(document.getElementById('keyValidity').value);
            
            if (isNaN(validity) || validity <= 0) {
                showToast('密钥有效期必须为正整数', 'error');
                return;
            }
            
            const config = {
                mode: document.getElementById('distributionMode').value,
                approvalFlow: document.getElementById('approvalFlow').value,
                keyValidity: validity,
                defaultAlgorithm: document.getElementById('defaultAlgorithm').value
            };
            
            localStorage.setItem('distributionConfig', JSON.stringify(config));
            showToast('配置保存成功！', 'success');
        }

        // 加载密钥申请
        function loadKeyRequests() {
            const requests = JSON.parse(localStorage.getItem('keyRequests')) || [];
            const distributions = JSON.parse(localStorage.getItem('keyDistributions') || []);
            const tbody = document.getElementById('requestsTableBody');
            tbody.innerHTML = '';

            if (requests.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="7" class="py-8 text-center text-gray-500">暂无密钥申请数据</td>
                    </tr>
                `;
                return;
            }

            requests.forEach(request => {
                // 检查该申请是否已生成密钥发行记录
                const hasDistribution = distributions.some(dist => dist.requestId === request.id);
                
                const row = document.createElement('tr');
                row.className = 'table-row border-b border-gray-100';
                let statusClass = 'status-pending';
                let statusText = '待审批';
                if (request.status === 'approved') {
                    statusClass = 'status-approved';
                    statusText = '已批准';
                } else if (request.status === 'rejected') {
                    statusClass = 'status-rejected';
                    statusText = '已拒绝';
                }
                row.innerHTML = `
                    <td class="py-3 px-4">${request.id}</td>
                    <td class="py-3 px-4">${request.applicant}</td>
                    <td class="py-3 px-4">${request.time}</td>
                    <td class="py-3 px-4">${request.keyType}</td>
                    <td class="py-3 px-4">${request.algorithm}</td>
                    <td class="py-3 px-4">
                        <div class="flex items-center gap-2">
                            <span class="status-badge ${statusClass}">${statusText}</span>
                            ${hasDistribution ? `<span class="text-xs text-green-600 flex items-center gap-1"><i class="fas fa-check-circle"></i>已发行</span>` : ''}
                        </div>
                    </td>
                    <td class="py-3 px-4">
                        <div class="flex gap-2">
                            <button onclick="viewRequest('${request.id}')" class="text-blue-600 hover:text-blue-800 p-1 rounded-full hover:bg-blue-50 transition-colors"><i class="fas fa-eye"></i></button>
                            ${request.status === 'pending' ? `
                                <button onclick="approveRequest('${request.id}')" class="text-green-600 hover:text-green-800 p-1 rounded-full hover:bg-green-50 transition-colors"><i class="fas fa-check"></i></button>
                                <button onclick="rejectRequest('${request.id}')" class="text-red-600 hover:text-red-800 p-1 rounded-full hover:bg-red-50 transition-colors"><i class="fas fa-times"></i></button>
                            ` : ''}
                        </div>
                    </td>
                `;
                tbody.appendChild(row);
            });
        }

        // 加载密钥发行记录
        function loadKeyDistributions() {
            const distributions = JSON.parse(localStorage.getItem('keyDistributions')) || [];
            const requests = JSON.parse(localStorage.getItem('keyRequests')) || [];
            const tbody = document.getElementById('distributionsTableBody');
            tbody.innerHTML = '';

            if (distributions.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="8" class="py-8 text-center text-gray-500">暂无密钥发行记录</td>
                    </tr>
                `;
                return;
            }

            distributions.forEach(distribution => {
                // 查找关联的申请信息
                const relatedRequest = requests.find(req => req.id === distribution.requestId);
                
                const row = document.createElement('tr');
                row.className = 'table-row border-b border-gray-100';
                row.innerHTML = `
                    <td class="py-3 px-4">${distribution.id}</td>
                    <td class="py-3 px-4">${distribution.keyId}</td>
                    <td class="py-3 px-4">${distribution.receiver}</td>
                    <td class="py-3 px-4">
                        <div>
                            <div class="font-medium">${relatedRequest ? relatedRequest.id : '无关联'}</div>
                            <div class="text-xs text-gray-500">申请人: ${relatedRequest ? relatedRequest.applicant : '未知'}</div>
                        </td>
                    <td class="py-3 px-4">${distribution.time}</td>
                    <td class="py-3 px-4">${distribution.validity}</td>
                    <td class="py-3 px-4">
                        <span class="status-badge status-completed">${distribution.status}</span>
                    </td>
                    <td class="py-3 px-4">
                        <div class="flex gap-2">
                            <button onclick="viewDistribution('${distribution.id}')" class="text-blue-600 hover:text-blue-800 p-1 rounded-full hover:bg-blue-50 transition-colors" title="查看发行详情"><i class="fas fa-eye"></i></button>
                            <button onclick="downloadFile('${distribution.file}')" class="text-purple-600 hover:text-purple-800 p-1 rounded-full hover:bg-purple-50 transition-colors tooltips" title="下载密钥文件">
                                <i class="fas fa-download"></i>
                            </button>
                            <button onclick="showFileInfo('${distribution.id}')" class="text-green-600 hover:text-green-800 p-1 rounded-full hover:bg-green-50 transition-colors tooltips" title="查看文件详情">
                                <i class="fas fa-info-circle"></i>
                            </button>
                        </div>
                    </td>
                `;
                tbody.appendChild(row);
            });
        }

        // 切换标签页
        function switchTab(tabName, event) {
            // 隐藏所有标签页内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.add('hidden');
            });

            // 移除所有标签按钮的激活状态
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.remove('active');
            });

            // 显示当前标签页内容
            document.getElementById(tabName + 'Tab').classList.remove('hidden');

            // 添加当前标签按钮的激活状态
            event.target.classList.add('active');
        }

        // 查看申请
        function viewRequest(requestId) {
            const requests = JSON.parse(localStorage.getItem('keyRequests')) || [];
            const request = requests.find(r => r.id === requestId);
            if (request) {
                const modal = document.getElementById('requestDetailModal');
                const content = document.getElementById('requestDetailContent');
                
                let statusClass = 'status-pending';
                let statusText = '待审批';
                if (request.status === 'approved') {
                    statusClass = 'status-approved';
                    statusText = '已批准';
                } else if (request.status === 'rejected') {
                    statusClass = 'status-rejected';
                    statusText = '已拒绝';
                }
                
                content.innerHTML = `
                    <div class="space-y-4">
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-600 mb-1">申请ID</label>
                                <div class="text-gray-800">${request.id}</div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-600 mb-1">申请人</label>
                                <div class="text-gray-800">${request.applicant}</div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-600 mb-1">申请时间</label>
                                <div class="text-gray-800">${request.time}</div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-600 mb-1">状态</label>
                                <span class="status-badge ${statusClass}">${statusText}</span>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-600 mb-1">密钥类型</label>
                                <div class="text-gray-800">${request.keyType}</div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-600 mb-1">算法</label>
                                <div class="text-gray-800">${request.algorithm}</div>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-600 mb-1">申请详情</label>
                            <div class="text-gray-800 border rounded-lg p-3 bg-gray-50">${request.details}</div>
                        </div>
                    </div>
                `;
                
                // 使用淡入动画显示模态框
                modal.classList.remove('hidden');
                setTimeout(function() {
                    modal.classList.add('modal-show');
                }, 10);
            }
        }

        // 批准申请
        function approveRequest(requestId) {
            console.log('开始批准申请:', requestId);
            showLoading();
            setTimeout(() => {
                try {
                    // 数据验证
                    if (!requestId) {
                        hideLoading();
                        showToast('参数错误！', 'error');
                        return;
                    }

                    console.log('读取localStorage数据...');
                    const requestsStr = localStorage.getItem('keyRequests');
                    const distributionsStr = localStorage.getItem('keyDistributions');
                    const keysStr = localStorage.getItem('keys');
                    const configStr = localStorage.getItem('distributionConfig');
                    
                    console.log('keyRequests数据:', requestsStr);
                    console.log('keyDistributions数据:', distributionsStr);
                    console.log('keys数据:', keysStr);
                    console.log('distributionConfig数据:', configStr);

                    const requests = JSON.parse(requestsStr || '[]');
                    const distributions = JSON.parse(distributionsStr || '[]');
                    const keys = JSON.parse(keysStr || '[]');
                    const config = JSON.parse(configStr || '{}');
                    
                    console.log('解析后的数据类型:');
                    console.log('requests:', typeof requests, Array.isArray(requests));
                    console.log('distributions:', typeof distributions, Array.isArray(distributions));
                    console.log('keys:', typeof keys, Array.isArray(keys));
                    console.log('config:', typeof config);
                    
                    // 找到申请
                    const request = requests.find(req => req.id === requestId);
                    console.log('找到的申请:', request);
                    
                    if (!request) {
                        hideLoading();
                        showToast('申请不存在！', 'error');
                        return;
                    }
                    
                    // 更新申请状态
                    const updatedRequests = requests.map(req => {
                        if (req.id === requestId) {
                            return { ...req, status: 'approved', approver: '系统管理员', approveTime: new Date().toISOString().slice(0, 19).replace('T', ' ') };
                        }
                        return req;
                    });
                    console.log('更新后的申请列表:', updatedRequests);
                    
                    // 生成密钥
                    const newKeyId = `KMS-${String(keys.length + 1).padStart(3, '0')}`;
                    const newKey = {
                        id: newKeyId,
                        name: `发行密钥-${newKeyId}`,
                        type: request.keyType.toLowerCase() === '主密钥' ? 'main' : 
                              request.keyType.toLowerCase() === 'kek' ? 'kek' : 'dek',
                        algorithm: request.algorithm,
                        protectionKey: null,
                        description: `通过申请 ${requestId} 发行的密钥`,
                        createdAt: new Date().toISOString().slice(0, 19).replace('T', ' '),
                        status: 'active'
                    };
                    console.log('生成的新密钥:', newKey);
                    keys.push(newKey);
                    
                    // 创建发行记录
                    const newDistributionId = `DIS-${String(distributions.length + 1).padStart(3, '0')}`;
                    const fileSize = `${(Math.random() * 5 + 1).toFixed(2)} MB`;
                    const newDistribution = {
                        id: newDistributionId,
                        keyId: newKeyId,
                        receiver: request.applicant,
                        time: new Date().toISOString().slice(0, 19).replace('T', ' '),
                        validity: `${config.keyValidity || 365}天`,
                        status: 'completed',
                        file: `kms-distribution-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}.zip`,
                        fileSize: fileSize,
                        fileType: 'ZIP',
                        checksum: `SHA256: ${Array(64).fill().map(() => Math.random().toString(16)[2]).join('')}`,
                        requestId: requestId
                    };
                    console.log('生成的新发行记录:', newDistribution);
                    distributions.push(newDistribution);
                    
                    // 保存所有数据
                    console.log('开始保存数据到localStorage...');
                    localStorage.setItem('keyRequests', JSON.stringify(updatedRequests));
                    localStorage.setItem('keyDistributions', JSON.stringify(distributions));
                    localStorage.setItem('keys', JSON.stringify(keys));
                    console.log('数据保存完成');
                    
                    loadKeyRequests();
                    loadKeyDistributions();
                    hideLoading();
                    showToast('申请已批准并生成密钥！', 'success');
                    console.log('申请批准成功完成');
                } catch (error) {
                    console.error('批准申请失败:', error);
                    console.error('错误堆栈:', error.stack);
                    hideLoading();
                    showToast('批准申请失败！错误详情请查看浏览器控制台', 'error');
                }
            }, 1500);
        }

        // 拒绝申请
        function rejectRequest(requestId) {
            showLoading();
            setTimeout(() => {
                try {
                    // 数据验证
                    if (!requestId) {
                        hideLoading();
                        showToast('参数错误！', 'error');
                        return;
                    }

                    const requests = JSON.parse(localStorage.getItem('keyRequests') || '[]');
                    const updatedRequests = requests.map(request => {
                        if (request.id === requestId) {
                            return { ...request, status: 'rejected' };
                        }
                        return request;
                    });
                    localStorage.setItem('keyRequests', JSON.stringify(updatedRequests));
                    loadKeyRequests();
                    hideLoading();
                    showToast('申请已拒绝！', 'success');
                } catch (error) {
                    console.error('拒绝申请失败:', error);
                    hideLoading();
                    showToast('拒绝申请失败！', 'error');
                }
            }, 800);
        }

        // 查看发行记录
        function viewDistribution(distributionId) {
            try {
                // 数据验证
                if (!distributionId) {
                    showToast('参数错误！', 'error');
                    return;
                }

                const distributions = JSON.parse(localStorage.getItem('keyDistributions') || '[]');
                const requests = JSON.parse(localStorage.getItem('keyRequests') || '[]');
                const distribution = distributions.find(d => d.id === distributionId);
                if (distribution) {
                    // 查找关联的申请信息
                    const relatedRequest = requests.find(req => req.id === distribution.requestId);
                    
                    const modal = document.getElementById('distributionDetailModal');
                    const content = document.getElementById('distributionDetailContent');
                    
                    content.innerHTML = `
                        <div class="space-y-4">
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-600 mb-1">发行ID</label>
                                    <div class="text-gray-800">${distribution.id}</div>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-600 mb-1">密钥ID</label>
                                    <div class="text-gray-800">${distribution.keyId}</div>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-600 mb-1">接收方</label>
                                    <div class="text-gray-800">${distribution.receiver}</div>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-600 mb-1">发行时间</label>
                                    <div class="text-gray-800">${distribution.time}</div>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-600 mb-1">有效期</label>
                                    <div class="text-gray-800">${distribution.validity}</div>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-600 mb-1">状态</label>
                                    <div class="text-gray-800">
                                        <span class="status-badge status-${distribution.status}">${distribution.status}</span>
                                    </div>
                                </div>
                                ${relatedRequest ? `
                                <div class="col-span-2">
                                    <label class="block text-sm font-medium text-gray-600 mb-1">关联申请信息</label>
                                    <div class="bg-blue-50 p-3 rounded-lg">
                                        <div class="grid grid-cols-2 gap-4">
                                            <div>
                                                <span class="text-sm font-medium text-gray-700">申请ID:</span> <span class="text-gray-800">${relatedRequest.id}</span>
                                            </div>
                                            <div>
                                                <span class="text-sm font-medium text-gray-700">申请人:</span> <span class="text-gray-800">${relatedRequest.applicant}</span>
                                            </div>
                                            <div>
                                                <span class="text-sm font-medium text-gray-700">申请时间:</span> <span class="text-gray-800">${relatedRequest.time}</span>
                                            </div>
                                            <div>
                                                <span class="text-sm font-medium text-gray-700">申请状态:</span> <span class="status-badge status-${relatedRequest.status}">${relatedRequest.status}</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                ` : ''}
                            </div>
                            <div class="mt-4 border-t pt-4">
                                <h3 class="text-lg font-medium text-gray-800 mb-2">密钥文件信息</h3>
                                <div class="grid grid-cols-2 gap-4">
                                    <div>
                                        <label class="block text-sm font-medium text-gray-600 mb-1">文件名</label>
                                        <div class="text-gray-800">${distribution.file}</div>
                                    </div>
                                    <div>
                                        <label class="block text-sm font-medium text-gray-600 mb-1">文件大小</label>
                                        <div class="text-gray-800">${distribution.fileSize}</div>
                                    </div>
                                    <div>
                                        <label class="block text-sm font-medium text-gray-600 mb-1">文件类型</label>
                                        <div class="text-gray-800">${distribution.fileType}</div>
                                    </div>
                                    <div>
                                        <label class="block text-sm font-medium text-gray-600 mb-1">校验和</label>
                                        <div class="text-gray-800 word-break-all">${distribution.checksum}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                    
                    // 显示模态框
                    modal.classList.remove('hidden');
                    modal.classList.add('modal-show');
                } else {
                    showToast('未找到发行记录！', 'error');
                }
            } catch (error) {
                console.error('查看发行记录失败:', error);
                showToast('查看发行记录失败！', 'error');
            }
        }

        // 查看文件详情
        function showFileInfo(distributionId) {
            try {
                console.log('showFileInfo called with ID:', distributionId);
                const distributions = JSON.parse(localStorage.getItem('keyDistributions') || '[]');
                const distribution = distributions.find(dist => dist.id === distributionId);
                
                if (distribution) {
                    // 使用简单的弹窗显示文件详情
                    const fileInfo = `文件详情：\n\n文件名：${distribution.file}\n文件大小：${distribution.fileSize || '未知'}\n文件类型：${distribution.fileType || 'ZIP'}\n创建时间：${distribution.time}\n校验和：${distribution.checksum || '未提供'}\n\n点击确定开始下载文件`;
                    
                    if (confirm(fileInfo)) {
                        // 用户确认后下载文件
                        downloadFile(distribution.file);
                    }
                } else {
                    console.error('未找到对应的发行记录:', distributionId);
                    showToast('未找到对应的发行记录！', 'error');
                }
            } catch (error) {
                console.error('查看文件详情失败:', error);
                showToast('查看文件详情失败！', 'error');
            }
        }

        // 下载文件
        function downloadFile(fileName) {
            try {
                // 数据验证
                if (!fileName) {
                    showToast('参数错误！', 'error');
                    return;
                }

                showLoading();
                
                // 模拟下载进度
                let progress = 0;
                const progressInterval = setInterval(() => {
                    progress += Math.random() * 20;
                    if (progress >= 100) {
                        progress = 100;
                        clearInterval(progressInterval);
                        
                        // 完成下载
                        setTimeout(() => {
                            showToast(`文件 ${fileName} 下载成功！`, 'success');
                            hideLoading();
                        }, 300);
                    }
                }, 100);
            } catch (error) {
                console.error('下载文件失败:', error);
                showToast('下载文件失败！', 'error');
            }
        }

        // 移除动态创建的模态框
        function removeModal(button) {
            console.log('removeModal called with button:', button);
            
            // 尝试多种方式查找模态框
            let modalOverlay = button.closest('.modal-overlay');
            
            if (!modalOverlay) {
                // 如果找不到，尝试查找父级的模态框
                modalOverlay = button.closest('.modal')?.parentElement;
            }
            
            if (!modalOverlay) {
                // 如果还是找不到，尝试通过类名查找所有模态框并移除
                console.log('Could not find modal with button parent, removing all modals');
                const allModals = document.querySelectorAll('.modal-overlay');
                allModals.forEach(function(modal) {
                    modal.remove();
                });
                return;
            }
            
            console.log('Found modal overlay:', modalOverlay);
            
            if (modalOverlay) {
                // 添加淡出动画
                modalOverlay.style.opacity = '0';
                setTimeout(function() {
                    modalOverlay.remove();
                    console.log('Modal removed successfully');
                }, 300);
            }
        }

        // 关闭模态框
        function closeModal(modalId) {
            const modal = document.getElementById(modalId);
            // 使用淡出动画隐藏模态框
            modal.classList.remove('modal-show');
            setTimeout(function() {
                modal.classList.add('hidden');
            }, 300);
        }

        // 点击模态框外部关闭
        window.addEventListener('click', (e) => {
            if (e.target.classList.contains('modal-overlay')) {
                // 使用淡出动画隐藏模态框
                e.target.classList.remove('modal-show');
                setTimeout(function() {
                    e.target.classList.add('hidden');
                }, 300);
            }
        });

        // ESC键关闭模态框
        window.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                document.querySelectorAll('.modal-overlay').forEach(modal => {
                    // 使用淡出动画隐藏模态框
                    modal.classList.remove('modal-show');
                    setTimeout(function() {
                        modal.classList.add('hidden');
                    }, 300);
                });
            }
        });

        // 动态计算高度
        function calculateDynamicHeight() {
            try {
                const mainContent = document.getElementById('main-content');
                if (mainContent) {
                    const viewportHeight = window.innerHeight;
                    const offsetTop = mainContent.offsetTop;
                    mainContent.style.minHeight = (viewportHeight - offsetTop) + 'px';
                }
            } catch (error) {
                console.error('计算高度失败:', error);
            }
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', () => {
            initData();
            loadDistributionConfig();
            loadKeyRequests();
            loadKeyDistributions();
            calculateDynamicHeight();
        });

        // 窗口大小变化时重新计算高度
        window.addEventListener('resize', () => {
            calculateDynamicHeight();
        });
    </script>
    </section>
    </article>
</body>
</html>